package com.mobilesales.android.activities.common;

import java.io.IOException;

import com.mobilesales.android.R;
import com.mobilesales.android.services.AuthServiceClient;
import com.mobilesales.android.services.Configuration;
import com.mobilesales.android.util.LogFlags;
import com.mobilesales.android.util.MessageBox;
import com.mobilesales.android.util.Settings;
import com.mobilesales.android.util.Settings.UnformatedEndpoints;
import com.mobilesales.android.infrastructure.SyncService;
import com.mobilesales.android.model.employees.*;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class SettingsActivity extends Activity {

	private EditText usernameField;
	private EditText passwordField;
	private EditText serverField;
	
	private Settings currentSettings;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		usernameField = (EditText)this.findViewById(R.id.userName);
		passwordField = (EditText)this.findViewById(R.id.password);
		serverField = (EditText)this.findViewById(R.id.serverAddress);
		currentSettings = this.loadSettings();
	}
	
	
	public void save(View v) {
		currentSettings = Settings.getSettings();
		String username = usernameField.getText().toString();
		String password = passwordField.getText().toString();
		String serverAddr = serverField.getText().toString();
		
		if (!validate()) {
			MessageBox.show(this, getString(R.string.ErrorValidate));
			return;
		}
		
		if (currentSettings==null)
			currentSettings = new Settings();
		currentSettings.setLogin(username);
		currentSettings.setPassword(password);
		currentSettings.setServerUrl(serverAddr);
		String regId = null;
		if (currentSettings.getC2dmRegistrationId()==null) {
			regId = this.getC2DMRegistrationId();
			if (regId!=null)
				currentSettings.setC2dmRegistrationId(regId);
			else {
				MessageBox.show(this, getString(R.string.ErrorC2DMRegistration));
				return;
			}
		}
		
		EmployeeAccess access = this.login(serverAddr, username, password, regId);
		if(access==null) {
			MessageBox.show(this, getString(R.string.ErrorLogin));
			return;
		}
		
		currentSettings.setEmployeeId(access.EmployeeId);
		currentSettings.setToken(access.Token);
		
		if (saveSettings(currentSettings)) {
			MessageBox.show(this, getString(R.string.SettingsSaved));
		}
		else {
			MessageBox.show(this, getString(R.string.ErrorSave));
		}
	}
	
	private boolean validate() {
		boolean valid = true;
		if (usernameField.getText().toString().equals("")) {
			usernameField.setError(getString(R.string.ErrorRequired));
			valid = false;
		}
		if (passwordField.getText().toString().equals("")) {
			passwordField.setError(getString(R.string.ErrorRequired));
			valid = false;
		}
		if (serverField.getText().toString().equals("")) {
			serverField.setError(getString(R.string.ErrorRequired));
			valid = false;
		}
		return valid;	
	}
	
	
	private boolean saveSettings(Settings settings) {
		try {
			settings.save();
			return true;
		} catch (IOException e) {}
		
		return false;
	}
	
	private Settings loadSettings() {
		Settings currentSettings = Settings.getSettings();
		if (currentSettings!=null) {

			String username = currentSettings.getLogin();
			if (username == null) username = "";
			String password = currentSettings.getPassword();
			if (password == null) password = "";
			String serverAddr = currentSettings.getServerUrl();
			if (serverAddr == null) serverAddr = "";
			
			usernameField.setText(username);
			passwordField.setText(password);
			serverField.setText(serverAddr);
		}
		return currentSettings;
	}

	public void synchronize(View v) {
		SyncService syncService = new SyncService(this);
		if (syncService.synchronize())
			MessageBox.show(this, getString(R.string.SyncSuccessful));
		else
			MessageBox.show(this, getString(R.string.ErrorSync));
	}
	
	private String getC2DMRegistrationId() {
		
		// TODO: get C2DM registration ID
		
		return "666-the-number-of-the-beast";
	}
	
	
	private EmployeeAccess login(String serverUrl, String username, String password, String c2dmRegId) {
		String url = String.format(UnformatedEndpoints.AuthEndpoint, serverUrl);
		Configuration conf = new Configuration(url);
		AuthServiceClient authService = new AuthServiceClient(conf);
		EmployeeAccess access = null;
		try {
			access = authService.Login(username, password, c2dmRegId);
		} 
		catch (Exception e) {
			Log.e(LogFlags.RestService, "Could not login on server", e);
		}
		return access;
	}
}
